package com.xiaofeng.oss.adapter;

import com.xiaofeng.oss.entity.FileInfo;
import com.xiaofeng.oss.adapter.StorageAdapter;
import com.xiaofeng.oss.util.MinioUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2024/02/02/14:21
 * @Description:
 */
public class MinioStorageAdapter implements StorageAdapter {

    @Resource
    private MinioUtil minioUtil;

    /**
     * minioUrl
     */
    @Value("${minio.url}")
    private String url;


    @Override
    @SneakyThrows
    public void createBucket(String bucket) {
        minioUtil.createBucket(bucket);
    }

    @Override
    @SneakyThrows
    public void uploadFile(MultipartFile uploadFil, String bucket, String objectName) {
        minioUtil.createBucket(bucket);
        if (objectName != null) {
            minioUtil.uploadFile(uploadFil.getInputStream(),bucket,objectName + "/" + uploadFil.getName());
        }else {
            minioUtil.uploadFile(uploadFil.getInputStream(),bucket,uploadFil.getName());
        }
    }

    @Override
    @SneakyThrows
    public List<String> getAllBucket() {
        return  minioUtil.getAllBucket();
    }

    @Override
    @SneakyThrows
    public List<FileInfo> getAllFiles(String bucket) {
        return minioUtil.getAllFiles(bucket);
    }

    @Override
    @SneakyThrows
    public InputStream downloadFile(String bucket, String objectName) {
        return minioUtil.downloadFile(bucket, objectName);
    }

    @Override
    @SneakyThrows
    public void deleteBucket(String bucket) {
        minioUtil.deleteBucket(bucket);
    }

    @Override
    @SneakyThrows
    public void deleteFile(String bucket, String objectName) {
        minioUtil.deleteFile(bucket, objectName);
    }

    @Override
    @SneakyThrows
    public void updateFile(MultipartFile uploadFile, String bucket, String objectName) {
        minioUtil.createBucket(bucket);
        if(objectName != null){
            minioUtil.uploadFile(uploadFile.getInputStream(),bucket,objectName + "/" + uploadFile.getOriginalFilename());
        }else {
            minioUtil.uploadFile(uploadFile.getInputStream(),bucket,uploadFile.getOriginalFilename());
        }
    }

    @Override
    @SneakyThrows
    public String getUrl(String bucket, String objectName) {
        return url + "/" + bucket + "/" + objectName;
    }
}
